<template>
  <view class="login-page">
    <view v-if="loginPhone">
      <view class="login_box">
        <view class="login_box_bgi">
          <view style="margin-left: 60rpx; font-size: 30px; color: #000; font-weight: bold; text-align: center"> 欢迎登录👏</view>
          <view style="margin-left: 60rpx; color: #999999">登录账号即可查看更多精彩资讯 </view>
        </view>
        <div class="bw" style="width: 90%; margin: 0 auto; margin-top: 79rpx">
          <image
            :src="
              loginTab
                ? 'https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/04/08/%E7%BC%96%E7%BB%84%205@2x_20250408174512A008.png'
                : 'https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/03/17/bg_login_20250317145715A006.png'
            "
            style="width: 100%; height: 601rpx; z-index: -1"
          >
          </image>
          <div style="display: flex; justify-content: space-between; padding: 0 120rpx; margin-top: -573rpx">
            <span @click="loginTab = true">手机号登录</span>
            <span @click="(loginPhone = false), (loginTab = false)">快捷登录</span>
            <!-- <span @click="loginTab = false">账号登录</span> -->
          </div>
          <view style="padding: 40rpx 44rpx; margin-top: 50rpx">
            <div class="input-label" style="margin-top: 20rpx">手机号</div>
            <view class="input-field">
              <u-input
                border="surround"
                prefixIconStyle="width: 36rpx; height: 32rpx; padding-right: 22rpx"
                prefixIcon="https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/03/17/zhanghao_20250317150010A008.png"
                maxlength="11"
                type="text"
                placeholder="请输入手机号"
                v-model="account"
              ></u-input>
            </view>
            <div v-if="!loginTab" class="input-label" style="margin-top: 20rpx">密码</div>
            <div v-if="!loginTab" class="input-field">
              <u-input
                prefixIconStyle="width: 36rpx; height: 32rpx; padding-right: 22rpx"
                prefixIcon="https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/03/17/mima_20250317145953A007.png"
                class="input_class"
                placeholder="请输入密码"
                v-model="password"
                :password="passwordType"
              >
                <template v-slot:suffix>
                  <u-icon size="50" :name="passwordIcon" @click.stop="togglePasswordVisibility"></u-icon>
                </template>
              </u-input>
            </div>
            <div v-if="loginTab" class="input-label" style="margin-top: 20rpx">验证码</div>
            <div v-if="loginTab" class="input-field">
              <u-input
                prefixIconStyle="width: 36rpx; height: 32rpx; padding-right: 22rpx"
                prefixIcon="https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/03/17/mima_20250317145953A007.png"
                class="input_class"
                placeholder="请输入验证码"
                v-model="captcha"
                type="number"
                maxlength="6"
              >
                <template v-slot:suffix>
                  <button class="eye-icon" style="height: 25px; line-height: 25px; padding: 0 10px" v-show="isCode">{{ code_time }}秒后重新获取</button>
                  <button class="eye-icon" @click="code" style="background: red; height: 25px; line-height: 25px; color: #fff; padding: 0 10px" v-show="!isCode" :disabled="sendingCode">
                    {{ sendingCode ? "发送中..." : "获取验证码" }}
                  </button>
                </template>
              </u-input>
            </div>
          </view>
        </div>

        <div style="margin: 0 auto">
          <button class="login_btn" @click="gotoLogin" :disabled="loggingIn">
            {{ loggingIn ? "登录中..." : "立即登录" }}
          </button>
        </div>
      </view>
    </view>
    <view v-if="!loginPhone">
      <view class="login_box">
        <view class="login_box_bgi">
          <view style="margin-left: 60rpx; font-size: 30px; color: #000; font-weight: bold; text-align: center"> Hello！</view>
          <view style="margin-left: 60rpx; color: #999999">欢迎来到智享优圈 </view>
        </view>
        <div class="bw" style="height: 600rpx">
          <view class="login_box_bgi2" style="display: flex; align-items: center; justify-content: center">
            <view style="font-size: 34px; color: #000; font-weight: bold; text-align: center"> 智享优圈</view>
            <view style="color: #999999; font-family: fangsong; margin-top: 5px">登录账号即可查看更多精彩资讯 </view>
          </view>
        </div>

        <div style="margin: 0 auto">
          <button class="login_btn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">同意协议并手机号快捷登录</button>
        </div>
      </view>
    </view>
    <view style="margin-top: 50rpx">
      <u-divider textSize="24" text="其他登录方式"></u-divider>
      <view style="display: flex; flex-direction: column; align-items: center; justify-content: center" v-if="!loginPhone" @click="(loginPhone = true), (loginTab = true)">
        <image style="width: 30px; height: 30px" src="https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/06/04/手机登录验证_20250604165221A014.png"> </image>
        <span>手机验证</span>
      </view>
      <view
        style="display: flex; flex-direction: column; align-items: center; justify-content: center"
        v-if="loginPhone"
        @click="
          loginPhone = false;
          loginTab = false;
        "
      >
        <image style="width: 30px; height: 30px" src="https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/06/03/快捷登录_20250603140432A021.png"> </image>
        <span>快捷登录</span>
      </view>
    </view>
  </view>
</template>

<script>
import { programlogin, phoneAndPassword, getUserPhoneNumber } from "../../utils/request_api.js";
import { isPointInPolygon } from "../../common/gps.js";
import { newUserIntegral } from "../../utils/request_api.js";

export default {
  data() {
    return {
      loginPhone: false,
      loggingIn: false,
      loginTab: false,
      account: "",
      password: "",
      authKey: "",
      passwordType: true,
      passwordIcon: "eye",
      ebMerId: "",
      userType: "",
      code_time: 60,
      captcha: "" /* 短信验证码字段 */,
      isCode: false,
      sendingCode: false,
      amount: "",
      yuanphone: "",
      givephone: "",
      nickName: "",
      shareCode: "",
    };
  },
  onLoad(options) {
    if (options.shareId) {
      this.ebMerId = options.shareId;
      this.userType = 3;
    } else {
      this.ebMerId = uni.getStorageSync("ebMerId");
      this.userType = uni.getStorageSync("userType");
    }

    this.amount = options.amount || "";
    this.yuanphone = options.yuanphone || "";
    this.nickName = options.nickName || "";
    this.givephone = options.givephone || "";
    this.shareCode = options.shareCode || "";

    // 获取微信登录code
    this.showloginJs();
  },
  methods: {
    showloginJs() {
      let that = this;
      let storedOpenID = uni.getStorageSync("openID");
      if (storedOpenID) {
        this.authKey = storedOpenID;
      } else {
        uni.login({
          provider: "weixin",
          success: (res) => {
            if (res.code) {
              that.wechatLogin(res.code);
            } else {
              console.error("登录失败:", res.errMsg);
              uni.showToast({
                title: "微信登录失败，请稍后再试",
                icon: "none",
              });
            }
          },
          fail: (err) => {
            console.error("登录失败:", err);
            uni.showToast({
              title: "微信登录失败，请稍后再试",
              icon: "none",
              duration: 2000,
            });
            // 延迟返回上一页
            setTimeout(() => {
              uni.navigateBack();
            }, 2000);
          },
        });
      }
    },

    wechatLogin(code) {
      var that = this;
      wx.getUserInfo({
        success(res) {
          const { nickName, avatarUrl, gender } = res.userInfo;
          programlogin({ code, avatar: avatarUrl, nickName, sex: gender }).then((response) => {
            const data = response.data;
            that.authKey = data.key;
            if (data.type === "login") {
              // 已注册用户直接登录
              uni.setStorageSync("uid", data.uid);
              uni.setStorageSync("token", data.token);
              uni.setStorageSync("userInfo_data", data);
              uni.setStorageSync("openID", data.key);
              that.handleLoginSuccess();
            } else {
              // 未注册用户需要继续登录流程
              that.loggingIn = false;
            }
          });
        },
        fail: () => {
          uni.showToast({
            title: "您需要授权，才能获取您的信息！",
            icon: "none",
            duration: 2000,
          });
          // 延迟返回上一页
          setTimeout(() => {
            uni.navigateBack();
          }, 2000);
        },
      });
    },

    getPhoneNumber(e) {
      if (e.detail.code && e.detail.errMsg == "getPhoneNumber:ok") {
        getUserPhoneNumber(e.detail).then((res) => {
          if (res.code == 200 && res.data.errmsg == "ok") {
            let that = this;
            this.account = res.data.phone_info.phoneNumber;
            this.gotoLogin();
          } else {
            uni.showToast({
              title: res.message,
              icon: "none",
            });
          }
        });
      }
    },

    sendSmsCode() {
      this.code_time = 60;
      this.initTime();
      this.isCode = true;
    },

    initTime() {
      this.timer = setInterval(() => {
        this.code_time--;
        if (this.code_time == 0) {
          clearInterval(this.timer);
          this.isCode = false;
        }
      }, 1000);
    },

    // 获取验证码
    async code() {
      let that = this;
      if (!that.account)
        return uni.showToast({
          title: "请输入正确的手机号码",
          icon: "none",
        });
      if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(that.account))
        return uni.showToast({
          title: "请输入正确的手机号码",
          icon: "none",
        });
      this.sendingCode = true; // 设置正在发送验证码状态
      var params = {
        phone: that.account,
      };
      uni.request({
        url: "https://www.wantongkonggu.cn/api/frontApph7/sendCode",
        data: "\r\n--XXX" + '\r\nContent-Disposition: form-data; name="phone"' + "\r\n" + "\r\n" + that.account + "\r\n--XXX",
        method: "POST",
        header: {
          "Authori-zation": "",
          "Content-Type": "multipart/form-data; boundary=XXX",
        },
        timeout: 10000,
        noAuth: true,
        success: (res) => {
          if (res.data.code == 200) {
            that.sendSmsCode();
            uni.showToast({
              title: "发送成功",
              icon: "none",
            });
            that.sendingCode = false; // 重置发送验证码状态
          } else {
            uni.showToast({
              title: "发送失败" + res.data.message,
              icon: "none",
            });
            that.sendingCode = false; // 重置发送验证码状态
          }
        },
        fail: (err) => {
          uni.showToast({
            title: "发送失败" + err,
            icon: "none",
          });
          that.sendingCode = false; // 重置发送验证码状态
        },
      });
    },

    togglePasswordVisibility() {
      // 切换密码显示与隐藏
      this.passwordType = this.passwordType === true ? false : true;
      // 切换眼睛图标
      this.passwordIcon = this.passwordIcon === "eye" ? "eye-off" : "eye";
    },

    gotoLogin() {
      let that = this;
      const phonePattern = /^1[3-9]\d{9}$/;
      if (!phonePattern.test(this.account) && this.loginTab && this.loginPhone) {
        uni.showToast({
          title: "请输入有效的手机号",
          icon: "none",
        });
        return;
      }
      if (this.loginTab && this.loginPhone && !this.captcha)
        return uni.showToast({
          title: "请输入验证码",
          icon: "none",
        });

      this.loggingIn = true; // 设置正在登录状态

      var params = {
        phone: this.account,
        password: this.password,
        captcha: this.captcha,
        key: this.authKey,
        type: "routine",
        codeOrPassword: this.loginTab ? "1" : "3",
        inviterLinkId: this.ebMerId ? this.ebMerId : "",
        inviteeType: this.userType,
      };

      phoneAndPassword(params)
        .then((res1) => {
          if (res1.code === 200) {
            if (res1.data.isNew == true && res1.data.isNew != null) {
              let uid = res1.data.uid;
              let location;
              let giveIntegralLs = res1.data.giveIntegralLs;

              uni.getLocation({
                type: "wgs84",
                success: function (res2) {
                  uni.setStorageSync("user_latitude", res2.latitude);
                  uni.setStorageSync("user_longitude", res2.longitude);
                  location = {
                    latitude: res2.latitude,
                    longitude: res2.longitude,
                  };
                  var isRule = false;
                  var ruleId = "";
                  for (let index = 0; index < giveIntegralLs.length; index++) {
                    if (!isRule) {
                      var element = giveIntegralLs[index].area;
                      var gps = JSON.parse(element);
                      var isInside = isPointInPolygon(location, gps);
                      if (isInside) {
                        ruleId = giveIntegralLs[index].id;
                        isRule = true;
                      }
                    }
                  }
                  if (isRule) {
                    newUserIntegral({ uid: uid, type: that.userType, sysConfigGiveIntegralId: ruleId, enrollArea: JSON.stringify(location) }).then((res4) => {
                      setTimeout(() => {
                        that.handleLoginSuccess(res1);
                      }, 100);
                    });
                  } else {
                    that.handleLoginSuccess(res1);
                  }
                },
                fail: function (err) {
                  console.error("获取定位失败:", err);
                  // 根据错误类型给出不同的提示
                  if (err.errMsg && err.errMsg.includes("auth deny")) {
                    uni.showToast({
                      title: "请授权位置权限以正常使用",
                      duration: 2000,
                      icon: "none",
                    });
                  } else {
                    uni.showToast({
                      title: "获取定位失败，请检查手机定位是否开启",
                      duration: 2000,
                      icon: "none",
                    });
                  }
                  that.handleLoginSuccess(res1);
                },
              });
            } else {
              this.handleLoginSuccess(res1);
            }
          } else {
            uni.showToast({
              title: res1.message,
              icon: "none",
            });
            this.loggingIn = false; // 重置正在登录状态
          }
        })
        .catch((err) => {
          console.error("登录请求失败", err);
          uni.showToast({
            title: "登录请求失败，请稍后再试",
            icon: "none",
          });
          this.loggingIn = false; // 重置正在登录状态
        });
    },

    handleLoginSuccess(resData) {
      let res1 = resData || uni.getStorageSync("userInfo_data");
      if (res1) {
        uni.setStorageSync("userInfo_data", res1.data || res1);
        uni.setStorageSync("uid", (res1.data || res1).uid);
        uni.setStorageSync("token", (res1.data || res1).token);
        uni.setStorageSync("openID", (res1.data || res1).key);
      }

      uni.showToast({
        title: "登录成功！",
        icon: "none",
      });

      // 登录成功后处理跳转逻辑
      // 商户邀请  返回商户首页
      if (this.userType == 1) {
        // 水站单独判断
        if (this.ebMerId == "1751873058997917") {
          uni.redirectTo({
            url: "/pages_h5/local_life/detailIndex?id=" + this.activeId + "&businessId=" + this.ebMerId + "&isLaundry=" + this.isLaundry,
          });
        } else {
          uni.redirectTo({
            url: "/pages_h5/index/components/detail?shareMerIdBack=" + this.ebMerId,
          });
        }
      } else if (this.givephone != "") {
        uni.showToast({
          title: "领取失败,请检查收取人手机号是否正确",
          icon: "none",
        });
        this.givephone = "";
        setTimeout(() => {
          uni.navigateBack({ delta: 1 });
        }, 800);
      } else if (this.amount != "" && this.yuanphone != "" && this.nickName != "" && this.givephone != "" && this.shareCode != "") {
        /* 平台积分拆分 */
        uni.navigateTo({
          url: "/pages_h5/index/components/inviteWuyejifen?amount=" + this.amount + "&yuanphone=" + this.yuanphone + "&nickName=" + this.nickName + "&shareCode=" + this.shareCode,
        });
      } else {
        // 默认跳转到个人中心
        uni.switchTab({
          url: "/pages_h5/myCenter/index",
        });
      }
    },
  },

  onUnload() {
    // 页面卸载时清除定时器
    if (this.timer) {
      clearInterval(this.timer);
    }
  },
};
</script>

<style lang="scss" scoped>
.login-page {
  background-color: #fff;
  min-height: 100vh;
}

.input_CLASDAD {
  width: 95%;
  margin-left: 2.5%;
  height: 70rpx;
  line-height: 70rpx;
  padding-left: 10px;
  border: 1px solid #999;
  border-radius: 10px;
  font-size: 26rpx;
  margin-top: 40rpx;
}

.input-item {
  display: flex;
  justify-content: space-between;
  width: 100%;
  height: 86rpx;
  margin-bottom: 38rpx;
  position: relative;

  .eye-icon {
    position: absolute;
    right: 20rpx;
    /* 调整眼睛图标的右边距 */
    top: 50%;
    transform: translateY(-50%);
    z-index: 10;
    width: 36rpx;
    height: 36rpx;
  }

  .code {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 220rpx;
    height: 86rpx;
    margin-left: 30rpx;
    background: rgba(233, 51, 35, 0.05);
    font-size: 28rpx;
    border-radius: 43rpx;

    &[disabled] {
      background: rgba(0, 0, 0, 0.05);
      color: #999;
    }
  }
}

.input_class {
  flex: 1;
  width: 100%;
  display: block;
  height: 100%;
  padding-left: 40rpx;
  padding-right: 50rpx;
  /* 确保眼睛图标不会覆盖输入的文字 */
  border-radius: 43rpx;
  border: 1px solid #dcdcdc;
  font-size: 24rpx;
}

.login_box {
  height: 100%;
}

.login_box_bgi {
  background-image: url("https://www.wantongkonggu.cn/crmebimage/profile/upload/2025/04/08/矩形 + 椭圆形蒙版@2x_20250408163607A007.png");
  height: 855rpx;
  width: 100%;
  background-size: 100% 100%;
  display: flex;
  /* align-items: center; */
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
  margin-bottom: -400rpx;
}

.login_box_bgi2 {
  backdrop-filter: blur(0rpx) brightness(100%);
  margin-bottom: 10px;
  border-radius: 10px;
  height: 100%;
  width: 100%;
  background-size: 100% 100%;
  display: flex;
  /* align-items: center; */
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
  margin-bottom: -400rpx;
}

.login_box_bgi_kuaijie {
  margin-bottom: 122rpx;
  background-color: #fff;
  height: 855rpx;
  width: 100%;
  background-size: 100% 100%;
  display: flex;
  /* align-items: center; */
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

/* 小程序复制 */
.logo-top {
  width: 100%;
  height: 314px;
}

.logo-container {
  text-align: center;
}

.logo {
  width: 160rpx;
  height: 40rpx;
}

.welcome-text {
  margin-top: 60rpx;
  font-size: 36rpx;
  letter-spacing: 2px;
  font-weight: 500;
  text-align: center;
  font-family: "Arial", sans-serif;
  padding-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.input-label {
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 24rpx;
  color: #1a1a1a;
  line-height: 33rpx;
  text-align: left;
  font-style: normal;
}

.input-field {
  margin-top: 10rpx;
  background-color: #f8f8f8;
  height: 80rpx;
  border-radius: 15rpx;
  display: flex;
  align-items: center;
}

.input_class {
  width: 100%;
  height: 60rpx;
  padding: 5rpx 10rpx;
  border: none;
  /* 去除未选中状态边框 */
  outline: none;
  /* 去除选中状态边框 */
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 24rpx;
  line-height: 33rpx;
  text-align: left;
  background: aliceblue;
  border-radius: 20rpx;
  margin: 20rpx 0;
}

.captcha-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.captcha-image {
  width: 400rpx;
  height: 80rpx;
  cursor: pointer;
}

button {
  height: 80rpx;
  line-height: 80rpx;
  background-color: #00dc88;
  color: #fff;
  border: none;
  font-size: 30rpx;
  width: 100%;

  &[disabled] {
    background: #cfd3de;
  }
}

.falsecalss {
  background: #cfd3de;
}

.register-link {
  margin-top: 50rpx;
  text-align: center;
  font-size: 13px;
  color: #999;
  letter-spacing: 3px;
  cursor: pointer;
}

button {
  height: 80rpx;
  line-height: 80rpx;
  background-color: #00dc88;
  color: #fff;
  border: none;
  font-size: 30rpx;
  width: 100%;

  &[disabled] {
    background: #cfd3de;
  }
}

.login_btn {
  width: 578rpx;
  height: 80rpx;
  background: linear-gradient(90deg, #ff5e0b 0%, #ff7c02 100%);
  border-radius: 15rpx;
  font-family: PingFangSC, PingFang SC;
  font-weight: 600;
  font-size: 26rpx;
  color: #ffffff;
  line-height: 37rpx;
  text-align: center;
  font-style: normal;
  display: flex;
  align-items: center;
  justify-content: center;

  &[disabled] {
    background: #cfd3de;
  }
}
</style>
